import React, {
  FC,
  KeyboardEvent,
  ReactElement,
  useCallback,
  useRef,
  useState
} from 'react';
import { useNavigate } from 'react-router-dom';
import { IconSend } from '@douyinfe/semi-icons';
import { Form, Button, Tabs, Toast } from '@douyinfe/semi-ui';
import type { FormApi } from '@douyinfe/semi-ui/lib/es/form';
import { useUpdateLoginUser } from '@/store';
import { useFloatText } from '@/hooks';
import * as tokenUtils from '@/utils/token';
import { doAccountLogin } from '@/services';

import './index.scss';

const LoginPage: FC = (): ReactElement => {
  const titleText = useFloatText({ message: `欢迎，请您先登录：` });
  const routeNavigate = useNavigate();
  const formApiRef = useRef<FormApi<Record<string, any>>>(null);
  const [loading, setLoading] = useState(false);
  const updateLoginUser = useUpdateLoginUser();

  const handleResetBtnClick = useCallback(() => {
    if (!formApiRef.current) {
      return;
    }
    formApiRef.current.reset();
  }, [formApiRef.current]);

  const handleLoginBtnClick = useCallback(async () => {
    if (!formApiRef.current) {
      return;
    };
    setLoading(true);

    try {
      const formApi = formApiRef.current;

      await formApi.validate();
      const formValues = formApi.getValues();

      // 调用登录接口, 获取信息
      const { message, code, data } = await doAccountLogin(formValues.username, formValues.password);

      if (code !== 0) {
        throw new Error(message);
      }

      tokenUtils.setToken(data.token);
      updateLoginUser(data);
      Toast.success('登录成功');
      routeNavigate('/service');
    } catch (e) {
      if (Object.prototype.toString.call(e) === '[object Error]') {
        Toast.error(`登录失败：${(e instanceof Error) ? e.message : 'Error'}`);
      }
    }

    setLoading(false);
  }, [formApiRef.current, routeNavigate]);

  const handleKeyboardDown = useCallback((e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleLoginBtnClick();
    }
  }, [handleLoginBtnClick]);

  return (
    <div className="container-full login-page">
      <div className="login-box">
        <nav>
          <IconSend />
          <span className="title">{titleText}</span>
        </nav>
        <Form
          layout="vertical"
          labelPosition="left"
          labelAlign="right"
          labelWidth="120px"
          initValues={{}}
          getFormApi={formApi => formApiRef.current = formApi}
        >
          <Tabs defaultActiveKey='1'>
            <Tabs.TabPane tab="账号密码登录" itemKey="1">
              <Form.Input
                label="用户名"
                field="username"
                placeholder="请输入用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              />
              <Form.Input
                label="密码"
                field="password"
                mode="password"
                placeholder="请输入密码"
                rules={[{ required: true, message: '请输入密码' }]}
                type="password"
                onKeyDown={handleKeyboardDown}
              />
            </Tabs.TabPane>
          </Tabs>
        </Form>

        <footer className="btn-group">
          <Button onClick={handleResetBtnClick}>
            重置
          </Button>
          <Button
            type="primary"
            theme="solid"
            loading={loading}
            onClick={handleLoginBtnClick}
          >
            登录
          </Button>
        </footer>
      </div>
    </div>
  );
}

export default LoginPage;